package hanjia;

import java.util.ArrayList;

/**
 * Description:
 * Author:    Dane
 * CreateTime:2025/2/12-下午4:33
 * Since  :   1.0
 * Version:   1.0
 */
public class LeetCode538 {

    public TreeNode convertBST(TreeNode root) {
        ArrayList<Integer> result = new ArrayList<>();
        inOrder(root, result);

        for (int i = result.size() - 2; i >= 0; i--) {
            result.set(i, result.get(i) + result.get(i + 1));
        }
        inOrder2(root,result);
        return root;


    }

    public void inOrder(TreeNode root, ArrayList<Integer> result) {

        if (root == null) {
            return;
        }
        inOrder(root.left, result);
        result.add(root.val);
        inOrder(root.right, result);


    }
    public void inOrder2(TreeNode root, ArrayList<Integer> result) {

        if (root == null) {
            return;
        }
        inOrder2(root.left,result);
        root.val=result.get(0 );
       result.remove(0);
        inOrder2(root.right,result);


    }
}
